/*
 * Copyright 2004-2008 the Seasar Foundation and the Others.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
package com.yakaten.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.arnx.jsonic.JSON;
import net.arnx.jsonic.JSONException;

import org.seasar.framework.log.Logger;
import org.seasar.framework.util.ResourceUtil;
import org.seasar.struts.annotation.Execute;

import com.yakaten.dto.AmazonItemInfoDto;
import com.yakaten.dto.AmazonPriceTaskDto;
import com.yakaten.exception.AmazonException;
import com.yakaten.exception.SystemException;
import com.yakaten.logic.AmazonPriceLogic;
import com.yakaten.login.AmazonLogin;
import com.yakaten.service.AmazonItemService;
import com.yakaten.service.AmazonPriceRunner;

public class AmazonPriceAction extends BaseAction {
	static Logger logger = Logger.getLogger(AmazonPriceAction.class);

	public String amazonItemId;
	public String amazonItemName;
	public String amazonItemPrice;
	public String sku;
	public String shopItemName;
	public String shopItemPrice;
	public String minPrice;
	public String taskNo;
	public String kankakuTime;
	public int status;
	public String quantity;
	public String condition;
	public int start;
	public int limit;

	@Execute(validator = false)
	public String index() {
		return "../amazonprice.jsp";
	}

	@Execute(validator = false)
	public String doGetAllTask() throws JSONException, IOException {
		List<AmazonPriceTaskDto> taskList = new ArrayList<AmazonPriceTaskDto>();
		int end = start+limit;
		try {
			taskList = new AmazonPriceLogic().getAllTaskList();

			if(end>taskList.size()){
				end=taskList.size();
			}
		} catch (SystemException e) {
			logger.error(e);
		}
//		response.getWriter().write(
//				"{\"totalCount\":\"" + taskList.size() + "\",\"results\":"
//						+ JSON.encode(taskList.subList(start, end)) + "}");
		response.getWriter().write(
				"{\"totalCount\":\"" + taskList.size() + "\",\"results\":"
						+ JSON.encode(taskList) + "}");
		return null;
	}

	@Execute(validator = false)
	public String doSetKankakuTime() throws IOException {
		try {
			AmazonPriceRunner.KENKAKU = Integer.parseInt(kankakuTime);
			response.getWriter().write("success");
		} catch (Exception e) {
			response.getWriter().write("error");
		}
		return null;
	}
	
//	@Execute(validator = false)
//	public String doReadExistData() throws IOException {
//		
//		try {
//			response.getWriter().write(new AmazonPriceLogic().readExistData());
//		} catch (SystemException e) {
//			response.getWriter().write("error");
//		}
//		return null;
//	}

	@Execute(validator = false)
	public String doGetKankakuTime() throws IOException {
		response.getWriter().write("" + AmazonPriceRunner.KENKAKU);
		return null;
	}

	@Execute(validator = false)
	public String addTask() throws IOException {
		AmazonPriceLogic logic = new AmazonPriceLogic();
		AmazonPriceTaskDto dto = new AmazonPriceTaskDto();

		try {

			if(logic.isExistTask(sku)){
				response.getWriter().write("exist");
				return null;
			}else{
				dto.setTaskNo(logic.getNewTaskNo());
				dto.setAmazonItemId(amazonItemId);
				dto.setAmazonItemName(amazonItemName);
				dto.setAmazonItemPrice(Integer.parseInt(amazonItemPrice));
				dto.setShopItemId(sku);
				dto.setShopItemName(shopItemName);
				dto.setShopItemPrice(Integer.parseInt(shopItemPrice));
				dto.setMinPrice(Integer.parseInt(minPrice));
				dto.setStartPrice(dto.getShopItemPrice());
				dto.setStartTime(new Date());
				dto.setStatus(1);
				dto.setQuantity(quantity);
				dto.setCondition(condition);
				logic.addTask(dto);
			}

		} catch (SystemException e) {
			logger.error(e);
		}

		response.getWriter().write("success");
		return null;
	}

	@Execute(validator = false)
	public String doUpdateTask() throws IOException {
		AmazonPriceLogic logic = new AmazonPriceLogic();
		AmazonPriceTaskDto dto = new AmazonPriceTaskDto();

		try {
			dto.setTaskNo(taskNo);
			dto.setAmazonItemId(amazonItemId);
			dto.setAmazonItemName(amazonItemName);
			dto.setAmazonItemPrice(Integer.parseInt(amazonItemPrice));
			dto.setShopItemId(sku);
			dto.setShopItemName(shopItemName);
			dto.setShopItemPrice(Integer.parseInt(shopItemPrice));
			dto.setMinPrice(Integer.parseInt(minPrice));
			dto.setStartPrice(dto.getShopItemPrice());
			dto.setStartTime(new Date());
			dto.setStatus(status);
			dto.setQuantity(quantity);
			dto.setCondition(condition);
			logic.updateTask(dto);

		} catch (SystemException e) {
			logger.error(e);
		}

		response.getWriter().write("success");
		return null;
	}

	@Execute(validator = false)
	public String updateTask() throws IOException {
		AmazonPriceLogic logic = new AmazonPriceLogic();
		try {
			logic.updateTaskStatus(taskNo, status);
		} catch (SystemException e) {
			logger.error(e);
		}
		response.getWriter().write("success");
		return null;
	}

	@Execute(validator = false)
	public String doDeleteTask() throws IOException {
		AmazonPriceLogic logic = new AmazonPriceLogic();
		try {
			if(taskNo!=null && taskNo.length()>0){
				String []taskNos = taskNo.split(",");
				for (int i=0;i<taskNos.length;i++){
					logic.deleteTask(taskNos[i]);
				}
			}
		} catch (SystemException e) {
			logger.error(e);
		}
		response.getWriter().write("success");
		return null;
	}

	@Execute(validator = false)
	public String doGetAmazonItemInfo() throws IOException {
		AmazonItemService amazonItemService = new AmazonItemService();
		try {
			AmazonItemInfoDto dto = amazonItemService.getItemInfo(amazonItemId,condition).get(0);
			response.getWriter().write(
					dto.getItemName() + "," + dto.getItemPrice()+ "," + dto.getShopName()+ "," + dto.getShippingPrice());
		} catch (AmazonException e) {
			logger.error(e);
			response.getWriter().write("取得失敗。");
		}
		return null;
	}

	@Execute(validator = false)
	public String doGetShopItemInfo() throws IOException {
		AmazonItemService service = new AmazonItemService();
		AmazonLogin login = new AmazonLogin();
		String userName = ResourceUtil
		.getProperties("yakaten.properties").getProperty(
		"amazon.login.userName");
		String password = ResourceUtil
		.getProperties("yakaten.properties").getProperty(
		"amazon.login.passwd");
		try {
			login.doLogin(userName, password);
			AmazonItemInfoDto  dto =service.getShopItemInfo(sku, amazonItemId);
			response.getWriter().write(
					dto.getShopItemName() + "," + dto.getShopItemPrice()+ "," + dto.getShopItemCondition()+ "," + dto.getShopItemQuantity());
		} catch (AmazonException e) {
			logger.error(e);
			response.getWriter().write("取得失敗。");
		}
		return null;
	}

}
